<template>
	
	<view class="content">
		<view class="c-footer">
			<view class="msg-box">
				<view class="msg">
					1、请保证本人验证。
				</view>
				<view class="msg">
					2、请使头像正面位于画框中。
				</view>
				<view class="msg">
					3、请使头像尽量清晰。
				</view>
				<view class="msg">
					4、请保证眼镜不反光，双眼可见。
				</view>
				<view class="msg">
					5、请保证无墨镜，口罩，面膜等遮挡物。
				</view>
				<view class="msg">
					6、请不要化浓妆，不要戴帽子。
				</view>
			</view>
			<view class="but" @click="snapshotPusher" v-if="!cilckSwitch">采集本人人脸</view>
		</view>
	</view>
	
	<!-- 参考https://www.jianshu.com/p/adcdbf83e1ff -->
</template>

<script>
	// import permission from '../../util/permission.js'
	import permision from "@/js_sdk/wa-permission/permission.js"
	export default {
		name: "camera",
		data() {
			
			return {
				type: '', //是否是补签拉起的人脸识别
				imgData: '',
				pusher: null,
				scanWin: null,
				faceInitTimeout: null,
				snapshTimeout: null,
				uploadFileTask: null,
				cilckSwitch: false, //防止多次点击
			};
		},
		methods: {
			//人脸比对
			handleFaceContrast(param) {
				uni.hideLoading()
				this.$http({
					url: '/API_AUTH/AppIaiFace/faceContrast.api',
					data: {
						...param,
						userid: uni.getStorageSync('userInfo').id
					}
				}).then(res => {
					console.log(res)
					if (res.data.compareResult == 1) {
						let pages = getCurrentPages(); //获取所有页面栈实例列表
						let nowPage = pages[pages.length - 1]; //当前页页面实例
						let prevPage = pages[pages.length - 2]; //上一页页面实例
						if (this.type == 'signOut') {
							prevPage.$vm.signOutXh = param.xh;
							prevPage.$vm.signOutPhotoPath = param.path
						} else {
							prevPage.$vm.xh = param.xh;
							prevPage.$vm.photoPath = param.path
						}
						uni.navigateBack()
					} else {
						uni.showToast({
							title: '人脸比对不通过，请重试',
							icon: 'none'
						})
						this.cilckSwitch = false
					}
				}).catch(err => {
					uni.showToast({
						title: '人脸比对不通过，请重试',
						icon: 'none'
					})
					this.cilckSwitch = false
				})
			},
			//初始化
			faceInit() {
				uni.showLoading({
					title: '请稍后...'
				})
				this.faceInitTimeout = setTimeout(async () => {
					//创建livepusher
					if (uni.getSystemInfoSync().platform === 'android') {
						const data1 = await permission.requestAndroidPermission(
							"android.permission.RECORD_AUDIO")
						const data2 = await permission.requestAndroidPermission("android.permission.CAMERA")
						console.log(data1, data2, 1111)
						if (data1 == 1 && data2 == 1) {
							this.pusherInit();
						}
					} else {
						this.pusherInit();
					}
					//覆盖在视频之上的内容，根据实际情况编写
					// this.scanWin = plus.webview.create('/hybrid/html/faceTip.html', '', {
					//  background: 'transparent'
					// });
					//新引入的webView显示
					// this.scanWin.show();
					//初始化上传本地文件的api
					this.initUploader()
				}, 500);
			},
			//初始化播放器
			pusherInit() {
				const currentWebview = this.$mp.page.$getAppWebview();
				this.pusher = plus.video.createLivePusher('livepusher', {
					url: '',
					top: '0px',
					left: '0px',
					width: '100%',
					height: '50%',
					position: 'absolute',
					aspect: '9:16',
					muted: false,
					'z-index': 999999,
					'border-radius': '50%',
				});
				currentWebview.append(this.pusher);
				//反转摄像头
				this.pusher.switchCamera();
				//开始预览
				this.pusher.preview();
				uni.hideLoading()
			},
			//初始化读取本地文件
			initUploader() {
				let that = this
				this.uploadFileTask = plus.uploader.createUpload(
					"完整的接口请求地址", {
						method: "POST",
						headers: {
							// 修改请求头Content-Type类型 此类型为文件上传
							"Content-Type": "multipart/form-data"
						}
					},
					// data：服务器返回的响应值 status: 网络请求状态码
					(data, status) => {
						// 请求上传文件成功
						if (status == 200) {
							console.log(data)
							// 获取data.responseText之后根据自己的业务逻辑做处理
							let result = JSON.parse(data.responseText);
							console.log(result.data.xh)
							that.handleFaceContrast({
								xh: result.data.xh,
								path: result.data.path
							})
						}
						// 请求上传文件失败
						else {
							uni.showToast({
								title: '上传图片失败',
								icon: 'none'
							})
							console.log("上传失败", status)
							that.cilckSwitch = false
							uni.hideLoading()
						}
					}
				);
			},
			//快照
			snapshotPusher() {
				if (this.cilckSwitch) {
					uni.showToast({
						title: '请勿频繁点击',
						icon: 'none'
					})
					return
				}
				this.cilckSwitch = true
				uni.showLoading({
					title: '正在比对，请勿退出'
				})
				let that = this
				this.snapshTimeout = setTimeout(() => {
					this.pusher.snapshot(
						e => {
							// this.pusher.close();
							// this.scanWin.hide();
							//拿到本地文件路径
							var src = e.tempImagePath;
							this.uploadImg(src)
							//获取图片base64
							// this.getMinImage(src);
						},
						function(e) {
							plus.nativeUI.alert('snapshot error: ' + JSON.stringify(e));
							that.cilckSwitch = false
							uni.hideLoading()
						}
					);
				}, 500);
			},
			//调用原生能力读取本地文件并上传
			uploadImg(imgPath) {
				this.uploadFileTask.addFile('file://' + imgPath, {
					key: "file" // 填入图片文件对应的字段名
				});
				//添加其他表单字段（参数） 两个参数可能都只支持传字符串
				// uploadFileTask.addData("参数名", 参数值);
				this.uploadFileTask.start();
			},
			//获取图片base64
			getMinImage(imgPath) {
				plus.zip.compressImage({
						src: imgPath,
						dst: imgPath,
						overwrite: true,
						quality: 40
					},
					zipRes => {
						setTimeout(() => {
							var reader = new plus.io.FileReader();
							reader.onloadend = res => {
								var speech = res.target.result; //base64图片
								console.log(speech.length);
								console.log(speech)
								this.imgData = speech;
							};
							reader.readAsDataURL(plus.io.convertLocalFileSystemURL(zipRes.target));
						}, 1000);
					},
					function(error) {
						console.log('Compress error!', error);
					}
				);
			},
		},
		onLoad(option) {
			//#ifdef APP-PLUS
			this.type = option.type
			this.faceInit();

			//#endif
		},
		onHide() {
			console.log('hide')
			this.faceInitTimeout && clearTimeout(this.faceInitTimeout);
			this.snapshTimeout && clearTimeout(this.snapshTimeout);
			// this.scanWin.hide();
		},
		onBackPress() {
			// let pages = getCurrentPages(); //获取所有页面栈实例列表
			// let nowPage = pages[pages.length - 1]; //当前页页面实例
			// let prevPage = pages[pages.length - 2]; //上一页页面实例
			// prevPage.$vm.xh = '11111';
			// prevPage.$vm.photoPath = '22222' 
			this.faceInitTimeout && clearTimeout(this.faceInitTimeout);
			this.snapshTimeout && clearTimeout(this.snapshTimeout);
			// this.scanWin.hide();
		},
		onUnload() {
			this.faceInitTimeout && clearTimeout(this.faceInitTimeout);
			this.snapshTimeout && clearTimeout(this.snapshTimeout);
			// this.scanWin.hide();
		},
	};
</script>

<style lang="scss" scoped>
	.but {
		margin: 50rpx auto 0;
		border-radius: 10px;
		width: 80%;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #008AFF;
		font-size: 16px;
		color: #FFFFFF;
	}

	.c-footer {

		width: 100%;
		position: fixed;
		top: 50%;
		left: 0;
		z-index: 10;
		padding: 30rpx 0;

		.msg-box {
			width: 80%;
			margin: 0 auto;
			text-align: left;

			.msg {
				margin-bottom: 15rpx;
				font-size: 13px;
				color: #666;
			}
		}
	}

	.img-data {
		width: 100%;
		height: auto;
	}

	.content {
		background-color: #fff;

	}
</style>